package com.spring.demo.untils.document.handle.conventer;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuweizhi
 * @since 2023/06/20 10:59
 */
public class SqlConverter {

    public static List<ClassMeta> parseClassMeta(String sqlStr) {
        if (StringUtils.isBlank(sqlStr)) {
            throw new RuntimeException("SQL 语句不允许为空");
        }
        sqlStr = sqlStr.toLowerCase();

        sqlStr = sqlStr.substring(sqlStr.indexOf("select") + 6, sqlStr.indexOf("from"));
        if (sqlStr.contains("*")) {
            throw new RuntimeException("SQL 语句不支持 * 字段解析");
        }

        List<ClassMeta> result = new ArrayList<>();
        String[] split = sqlStr.split(",");
        for (int i = 0; i < split.length; i++) {
            String filedValue = split[i];
            ClassMeta classMeta = new ClassMeta();
            classMeta.setIndex(i);
            if (filedValue.contains(" as ")) {
                String[] as = filedValue.split(" as ");
                classMeta.setName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, as[1].trim()));
            } else {
                if (filedValue.contains(".")) {
                    filedValue = filedValue.split("\\.")[1];
                }
                classMeta.setName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, filedValue).trim());
            }
            result.add(classMeta);

        }
        return result;
    }

}
